import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as ContacterViewAction from '../actions/contacterView'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'

import CrmTools from './crmTools';

import CustomerContact from './CustomerContact'  
import ContacterTrail from './contacter/ContacterTrail'

import WeaRightLeftLayout from './weaCrmRightLeft'
import {
    WeaReqTop ,
    WeaTab,
    WeaTop,
    WeaNewScroll  ,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
} from 'ecCom'

import {WeaErrorPage,WeaTools,WeaAlertPage} from 'ecCom'

import {Button,Form,Modal,message,Spin} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'

import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class ContacterView extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
        const {actions,location:{query}} = this.props;
        actions.setNowRouterCmpath('contacterView');
        actions.initDatas({operation:'edit',...query});
      
    }
    componentWillReceiveProps(nextProps) {

    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.title,nextProps.title)||
        !is(this.props.detailTabKey,nextProps.detailTabKey)||
        !is(this.props.conditioninfo,nextProps.conditioninfo)||
        !is(this.props.loading,nextProps.loading)||
        !is(this.props.canEdit,nextProps.canEdit)||
        !is(this.props.orderFields,nextProps.orderFields)||
        !is(this.props.contacterId,nextProps.contacterId)||
        !is(this.props.customerId,nextProps.customerId)||
        !is(this.props.hasright,nextProps.hasright)||
        !is(this.props.trailinfo,nextProps.trailinfo);
    }
    componentWillUnmount(){
    	// const {actions,isClearNowPageStatus} = this.props;
        // actions.unmountClear(isClearNowPageStatus);
        // actions.isClearNowPageStatus(false);
    }
    render() {
        let that = this;
        const {loading,actions,title,conditioninfo,detailTabKey,customerId,location,hasright,trailinfo} = this.props;
        let tabDatas = [
            {title:'联系人信息',key:"1"},
            {title:'工作轨迹',key:"2"},
        ];
        const contentH = jQuery(".wea-new-top-req-content").height();
        if(hasright == "-1"){
            return (
				<div className="align-center top40">
					<Spin size="large"></Spin>
				</div>);
        }else if(!hasright){
            return (
                <WeaAlertPage>
                    <div className="color-black">
                        对不起，您暂时没有权限
                    </div>
                </WeaAlertPage>);
        }else{
            return (
                <div>
                    <WeaReqTop
                        title={title}
                        loading={loading}
                        icon={<i className='icon-coms-crm' />}
                        tabDatas={tabDatas}
                        selectedKey={detailTabKey}
                        onChange={this.changeData.bind(this)}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={false}
                        dropMenuDatas={[]}
                    >
                    {//className="contacter-hrm-detail"
                            detailTabKey == "1" &&
                            <div >
                                <WeaRightLeftLayout  defaultShowLeft={false} leftCom={<WeaNewScroll height={contentH} children={<Form horizontal>{this.getSearchs()}</Form>} />}  >
                                    <div className="customer-contact-title">客户联系</div>
                                    <div className="customer-contact-bottomline"></div>
                                <CustomerContact ref="contactlogs" location={location} params={{from:"base",customerId:customerId}} />
                                </WeaRightLeftLayout>
                            </div>
                        }
                        {
                            detailTabKey == "2" &&
                                <ContacterTrail data = {trailinfo} />
                        }
                </WeaReqTop>
                </div>
            )
        }
    }
     getButtons() {
         const {canEdit,contacterId,actions} = this.props;
        let btnArr = [];
        btnArr.push(<Button type="primary" disabled={!canEdit} style={{marginRight:"20px"}}
             onClick={()=>{actions.deleteContracter(contacterId)}} >删除</Button>)
        return btnArr
    }
     changeData(key){
         const {actions} = this.props
        // const {requestid} = location.query;
        actions.setDetailTabKey(key);
    }
     getSearchs() {
         const {conditioninfo} = this.props;
         let conditionAttr = [];
         conditioninfo.map((item,index)=>{
            conditionAttr.push(
                <WeaSearchGroup needTigger={true} title={this.getTitle(index)} showGroup={this.isShowFields(index)} items={this.getFields(index)}/>
            );
         });
         return conditionAttr;
    }
    getTitle(index = 0) {
       const {conditioninfo} = this.props;
       return !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].title
    }
    isShowFields(index = 0) {
        const {conditioninfo} = this.props;
        return !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].defaultshow
    }
    // 0 常用条件，1 其他条件 
    getFields(index = 0) {
        const {conditioninfo,canEdit} = this.props;
        const fieldsData = !isEmpty(conditioninfo.toJS()) && conditioninfo.toJS()[index].items;
        let items = [];
        forEach(fieldsData, (field) => {
            items.push({
               com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {CrmTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field,this.callback)}
                    </FormItem>),
                colSpan:1
            })
        })
        return items;
    }
    callback=(field,value,id,name)=>{
       const {contacterId,actions } = this.props;
       let fit = field.formItemType.toUpperCase();
       const fieldName=field.domkey[0];
       let obj = {};
       if(( fit === "INPUT" ||fit === "TEXTAREA") && value !== field.value){
            if( field.viewAttr== 3 && value == ""){
                return false;
            }else{
                const params ={
                    contacterId:contacterId,
                    fieldName:field.domkey[0] , 
                    oldValue:field.value,   
                    newValue:value,    
                    fieldType:fit
                };
                actions.contacterEdit(params);
            }  
       }
       if(fit === "SELECT" || fit === "CHECKBOX" || fit === "BROWSER" || fit=== "DATEPICKER"){
             const params ={
                contacterId:contacterId,
                fieldName:field.domkey[0] , 
                oldValue:field.value,   
                newValue:value,    
                fieldType:fit
            };
                actions.contacterEdit(params);
       }
    }
   
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

ContacterView = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(ContacterView);

ContacterView = createForm({
	// onFieldsChange(props, fields) {
    //    // console.log({...fields});
    //     props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    // },
	// mapPropsToFields(props) {
	// 	return props.orderFields.toJS();
  	// }
})(ContacterView);

function mapStateToProps(state) {
	const {crmcontacterView} = state;
    return {
    	loading: crmcontacterView.get('loading'),
        title: crmcontacterView.get('title'),
        conditioninfo: crmcontacterView.get('conditioninfo'),
        detailTabKey: crmcontacterView.get('detailTabKey'),
        canEdit: crmcontacterView.get('canEdit'),
        orderFields:crmcontacterView.get('orderFields'),
        contacterId :crmcontacterView.get('contacterId'),
        customerId:crmcontacterView.get('customerId'),
        hasright:crmcontacterView.get('hasright'),
        trailinfo:crmcontacterView.get('trailinfo')
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...ContacterViewAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(ContacterView);
